package com.journey.org.ui.test

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.IBinder
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.startActivity

class PhoneService : Service() {

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    var mTm: TelephonyManager? = null
    var phoneListener: MyPhoneStateListener? = null

    override fun onCreate() {
        mTm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
        phoneListener = MyPhoneStateListener()
        mTm?.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE)
        super.onCreate()
    }

    @SuppressLint("MissingPermission")
    fun callPhone(phone: String) {
        val intent = Intent(Intent.ACTION_CALL)
        val data = Uri.parse("tel:$phone")
        intent.data = data
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }

    var index: Int = 0

    fun test() {
        if (index == 1) {
            callPhone("18275554434")
        } else if (index == 2) {
            callPhone("18308655373")
        }
    }

    inner class MyPhoneStateListener : PhoneStateListener() {
        override fun onCallStateChanged(state: Int, phoneNumber: String?) {
            super.onCallStateChanged(state, phoneNumber)
            println("电话状态：$state")
            println("电话号码：$phoneNumber")
            when (state) {
                // 空闲状态
                TelephonyManager.CALL_STATE_IDLE -> {
                    ++this@PhoneService.index
                    this@PhoneService.test()
                    println("空闲状态")
                }
                // 摘机状态，至少有个电话活动，该活动或是拨打或是通话
                TelephonyManager.CALL_STATE_OFFHOOK -> {
                    println("摘机状态，至少有个电话活动，该活动或是拨打或是通话")
                }
                // 响铃状态
                TelephonyManager.CALL_STATE_RINGING -> {
                    println("响铃状态")
                }
            }
        }
    }

    override fun onDestroy() {
        mTm?.listen(phoneListener, PhoneStateListener.LISTEN_NONE)
        super.onDestroy()
    }
}
